import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import * as gc from 'src/app/global/const';
import { Observable } from 'rxjs';
import { JsonResult } from '../model/JsonResult';
import { UUID } from 'angular2-uuid';
import { map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class RoadTripService {


  private path_pre = 'roadTrip';

  private url = {
    'deleteByPrimaryKey':gc.BACKEND_SERVER_ROOT + '/' + this.path_pre + '/deleteByPrimaryKey',
    'selectByPrimaryKey':gc.BACKEND_SERVER_ROOT + '/' + this.path_pre,
    'selectAll':gc.BACKEND_SERVER_ROOT + '/' + this.path_pre + '/selectAll',
    'saveOne':gc.BACKEND_SERVER_ROOT + '/' + this.path_pre,
    'insert':gc.BACKEND_SERVER_ROOT + '/' + this.path_pre + '/insert',
    'update':gc.BACKEND_SERVER_ROOT + '/' + this.path_pre + '/update',
    'selectByTableName':gc.BACKEND_SERVER_ROOT + '/' + this.path_pre + '/selectByTableName',
  }
  constructor(
    private http:HttpClient
  ) { }

  deleteByPrimaryKey(iid:number):Observable<JsonResult>{
    const url = this.url.deleteByPrimaryKey + '/' + iid;
    return this.http.delete<JsonResult>(url);
  }

  selectByPrimaryKey(iid:number):Observable<JsonResult>{
    const url = this.url.selectByPrimaryKey + '/' + iid;
    return this.http.get<JsonResult>(url);
  }

  selectAll():Observable<JsonResult>{

    let res$ = this.http.get<JsonResult>(this.url.selectAll);
    return res$.pipe(map(
      ( res:JsonResult ) =>{
        let data = res.data;
        data.forEach(ele => {
          ele.uuid = UUID.UUID();
        });

        return res;
      }
    ))

  }

  insert(record:RoadTrip):Observable<JsonResult>{
    return this.http.post<JsonResult>(this.url.insert,record);
  }

  update(record:RoadTrip):Observable<JsonResult>{
    return this.http.post<JsonResult>(this.url.update,record);
  }

  selectByTableName(tableName:string):Observable<JsonResult>{
    const url = this.url.selectByTableName + '/' + tableName;
    return this.http.get<JsonResult>(url);
  }

  saveOne(record:RoadTrip):Observable<JsonResult>{
    let iid:number = record.iid;
    if( iid === undefined || iid === null || iid === 0)
      return this.insert(record);
    else
      return this.update(record);
  }

}


// Author：chanchaw
// Generator Version：1.0 - 2019年11月16日 16点46分
// This Model Created：Tue Jan 07 2020 13:29:00 GMT+0800 (中国标准时间)
export class RoadTrip{
  iid:number;
  bill_date:Date;
  client:string;
  one_way:number;
  kilometer:number;
  kilometer_amount:number;
  oil_cost:number;
  oil_amount:number;
  business:string;
  remark:string;
  create_time:Date;
  bool_test:boolean;
  uuid:string;
  

  constructor(){
    this.uuid = UUID.UUID();
  }
}
